import { Component, OnInit, ViewChild, ElementRef, AfterViewInit, Input } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { Topology } from 'topology-core';
import { register as registerFlow } from 'topology-flow-diagram';
import {register as registerCustom} from '../shape/register';
import { Props } from './props/props.model';
import { TopologyData } from 'topology-core/models/data';
import { Line } from 'topology-core/models/line';
import { Tools,Item } from './tools/config';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { switchMap, map } from 'rxjs/operators';
import { SupDic, LbfService, HttpService } from 'lbf';
import { NzMessageService } from 'ng-zorro-antd';
@Component({
  selector: 'app-flowchart-one-item',
  templateUrl: './one-item.component.html',
  styleUrls: ['./one-item.component.less']
})
export class FlowchartOneItemComponent implements OnInit, AfterViewInit {


  @Input()
  delay = 0;


  @Input()
  id = ''
  @Input()
  name = ''

  start = {
    'id': 'start',
    'name': 'item',
    'tags': [],
    'text': '开始',
    'rect': {
      'x': 50,
      'y': 216,
      'width': 50,
      'height': 50,
      'center': { 'x': 404, 'y': 266 },
      'ex': 454,
      'ey': 316
    },
  }
  end = {
    'id': 'end',
    'name': 'rectangle',
    'text': '结束',
    'rect': {
      'x': 500,
      'y': 216,
      'width': 50,
      'height': 50,
      'center': { 'x': 404, 'y': 266 },
      'ex': 454,
      'ey': 316
    },
  }


  tools: any[] = Tools;
  mainItem = Item;
  data;
  selected: Props;
  nodes: any[] = [];

  selNodes: any;

  readonly = false;
  locked = false;
  canvas: Topology;
  canvasOptions = {
    on: (event: string, data: any) => { }
  }

  @ViewChild('one', { static: true }) one: ElementRef;
  constructor(
    public msgSrv: NzMessageService,
    private lbserver: HttpService,
  ) { }

  ngOnInit() {
    registerFlow();
    registerCustom();
    this.canvasOptions.on = this.onMessage
    // this.init()

    // const id = this.route.snapshot.paramMap.get('id');
    // const name = this.route.snapshot.paramMap.get('name');

  }

  ngAfterViewInit() {

    this.lbserver.lbservice('FLOW_QUERY', { para: { DAD017: this.id } }).then(res => {

      if (res) {
        if(res.para){
            // const para = JSON.parse(res.message.list[0].DAD038)
             this.data = res.para.data
        }
        else{
          this.init()
        }
      
      } 
      else {
        this.init()
        // this.msgSrv.error(res.errmsg)
      }
      setTimeout(() => {
        this.canvas = new Topology(this.one.nativeElement, this.canvasOptions);
        this.canvas.open(this.data);
        // this.canvas.data.pens = this.data.pens
        // this.topologySrv.canvasRegister();
        this.addNodeAttr(this.data)
        this.canvas.render();
        this.canvas.resize()
      }, this.delay
      )
    })


  }


  init() {
    this.start.text = this.name
    this.data = {
      nodes: [
      //  this.start,

      ], lines: []
    }


    // this.canvas.data = this.data
    // this.canvas.clearBkImg
  }

  onDrag(event: DragEvent, node: any) {
    event.dataTransfer.setData('Text', JSON.stringify(node.data));
    console.log('node :', node);
  }

  onMessage = (event: string, data: any) => {
    switch (event) {
      case 'node':
      case 'addNode':
        {
          console.log(data)
          this.nodes.forEach((node, index) => {
            if (node.id === data.id) {
              this.nodes.splice(index, 1);
            }
          });
          this.selNodes = [data];
          this.selected = {
            type: 'node',
            data
          };
          this.locked = data.locked;
          this.readonly = this.locked || !!this.canvas.data.locked;
        }
        break;
      case 'line':
      case 'addLine':
        this.selected = {
          type: 'line',
          data
        };
        this.locked = data.locked;
        this.readonly = this.locked || !!this.canvas.data.locked;
        break;
      case 'space':
        setTimeout(() => {
          this.selected = null;
          this.selNodes = null;
        });
        break;
      case 'moveOut':
      default:
        break;
    }
  }

  onChangeProps(props: any) {
    console.log(props.data)
    if (this.canvas.data.locked) {
      return;
    }
    switch (props.type) {
      case 'node':
      case 'addNode':
        this.canvas.updateProps(props.data);
        break;
      case 'line':
      case 'addLine':
        this.canvas.updateProps();
        break;
    }
  }

  onAnimateChange() {
    this.canvas.animate();
  }

  confirm() {
    console.log(this.canvas)
    this.fromAndTo(this.canvas.data)
  }
  fromAndTo(data: TopologyData) {

    data.pens.map((line) => {
      if (line instanceof Line)
        line.to.id && console.log('from :', line.from.id, ' to: ', line.to.id)
    })

  }

  save() {
    console.log(this.canvas)
    let flag = true
    this.canvas.data.pens.map(node=>{
      if(!this.nodeValid(node)){
          flag = false
      }
    })
    if (this.id && flag) {
      const data = this.canvas.data
       let items = this.itemsSelect(data.pens)
      let para = {
        data,
        DAD017: this.id,
        items,
      }
     
    //  let para = JSON.stringify(para1) + '<>' +JSON.stringify(items)+'<>'+this.id +'<>'

      this.lbserver.lbservice('FLOW_SAVE', { para }).then(res => {
        if (res.code > 0) {
          this.msgSrv.info('保存成功')
        } else {
          this.msgSrv.error(res.errmsg)
        }
      }
      )
    }else{
        this.msgSrv.error('请填写事项属性')
    }
  }


  itemsSelect(nodes){
      let arr = []
      nodes.map(node=>{
        if(node.name ==='item'){
          let obj = {
            text:node.text,
            DAD090:node.DAD090,
            DAD091:node.DAD091,
            DAD101:node.DAD101,
            DAD092:node.DAD092,
            DAD102:node.DAD102,
            DGB010:node.DGB010,
            TZDZ:node.TZDZ
          }
          arr.push(obj)
        }
      })

      return arr;
  }

  addNodeAttr(data){
    if(this.canvas.data.pens.length>0){
         this.canvas.data.pens.map((node,index)=>{
        if(data.pens[index].DAD090)
      // @ts-ignore
        node.DAD090 = data.pens[index].DAD090
        if(data.pens[index].DAD091)
        // @ts-ignore
        node.DAD091 = data.pens[index].DAD091
        if(data.pens[index].DAD101)
        // @ts-ignore
        node.DAD101 = data.pens[index].DAD101
        if(data.pens[index].DAD092)
        // @ts-ignore
        node.DAD092 = data.pens[index].DAD092
        if(data.pens[index].DAD102)
        // @ts-ignore
        node.DAD102 = data.pens[index].DAD102
        if(data.pens[index].DGB010)
        // @ts-ignore
        node.DGB010 = data.pens[index].DGB010
        // this.canvas.updateProps(data.pens[index]);
        if(data.pens[index].TZDZ)
        // @ts-ignore
        node.TZDZ = data.pens[index].TZDZ
    })
    }
 
  }
  // 校验事项属性
  nodeValid(node){
    if(node.name==="item")
    {
      if(node.DAD090 && node.DAD091 && node.DAD101 && node.DAD102 && node.DGB010){
      }else{
        return false;
      }
    }
    return true;
  }
  
}
